import Vue from "vue";
import VueRouter from "vue-router";
import { getConfig } from "@/utils/configAction";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "login",
    component: () => import("../views/Login.vue")
  },
  {
    path: "/register",
    name: "register",
    component: () => import("../views/Register.vue")
  },
  {
    path: "/direction",
    name: "direction",
    component: () => import("../views/Direction.vue")
  }
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes
});

router.beforeEach((to, from, next) => {
  const token = getConfig("token");

  const target = getConfig("target");

  const appid = getConfig("appid");

  if (token && to.name === "login") {
    return next({ name: "direction", query: { target, appid } });
  }

  if (!token && to.name === "direction") {
    return next({ name: "login", query: { target, appid } });
  }

  return next();
});

export default router;
